package com.ruoyi.exam.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.base.Joiner;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.exam.domain.QuestionBank;
import com.ruoyi.exam.domain.QuestionResult;
import com.ruoyi.exam.domain.req.TestQuestionReq;
import com.ruoyi.exam.mapper.QuestionBankMapper;
import com.ruoyi.exam.mapper.QuestionResultMapper;
import com.ruoyi.exam.service.IQuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.exam.mapper.TestQuestionsMapper;
import com.ruoyi.exam.domain.TestQuestions;
import com.ruoyi.exam.service.ITestQuestionsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 试题管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-01
 */
@Service
public class TestQuestionsServiceImpl implements ITestQuestionsService 
{
    @Autowired
    private TestQuestionsMapper testQuestionsMapper;

    @Autowired
    private QuestionResultMapper questionResultMapper;

    @Autowired
    private QuestionBankMapper questionBankMapper;

    @Autowired
    private IQuestionBankService questionBankService;

    /**
     * 查询试题管理
     * 
     * @param id 试题管理主键
     * @return 试题管理
     */
    @Override
    public TestQuestionReq selectTestQuestionsById(Long id)
    {
        //查询主表
        TestQuestions testQuestions = testQuestionsMapper.selectTestQuestionsById(id);
       //查询多的一方
        List<QuestionResult>  questionResults = questionResultMapper.getQuestionBankByTestQuestionId(id);
       //组装成VO
        TestQuestionReq testQuestionReqResult = BeanUtil.toBean(testQuestions, TestQuestionReq.class);
        testQuestionReqResult.setQuestionResultList(questionResults);


        return testQuestionReqResult;
    }

    /**
     * 查询试题管理列表
     * 
     * @param testQuestions 试题管理
     * @return 试题管理
     */
    @Override
    public List<TestQuestions> selectTestQuestionsList(TestQuestions testQuestions)
    {
        return testQuestionsMapper.selectTestQuestionsList(testQuestions);
    }

    /**
     * 新增试题管理
     * 
     * @param testQuestions 试题管理
     * @return 结果
     */
    @Override
    public int insertTestQuestions(TestQuestions testQuestions)
    {
        testQuestions.setCreateTime(DateUtils.getNowDate());
        return testQuestionsMapper.insertTestQuestions(testQuestions);
    }

    /**
     * 修改试题管理
     * 
     * @param testQuestions 试题管理
     * @return 结果
     */
    @Override
    public int updateTestQuestions(TestQuestions testQuestions)
    {
        testQuestions.setUpdateTime(DateUtils.getNowDate());
        return testQuestionsMapper.updateTestQuestions(testQuestions);
    }

    /**
     * 批量删除试题管理 一对多删除
     * 
     * @param ids 需要删除的试题管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTestQuestionsByIds(Long[] ids)
    {
        //先删除主表
        int delTestQuestionsResult = testQuestionsMapper.deleteTestQuestionsByIds(ids);
        //再删除多的一方
        int delQuestionsResult = questionResultMapper.deleteQuestionResultByTestQuestionIds(ids);
        return delTestQuestionsResult>0&&delQuestionsResult>0?1:0;
    }

    /**
     * 删除试题管理信息
     * 
     * @param id 试题管理主键
     * @return 结果
     */
    @Override
    public int deleteTestQuestionsById(Long id)
    {
        return testQuestionsMapper.deleteTestQuestionsById(id);
    }

    /**
     * @Description: 试题的一对多添加
     * @Param: [testQuestionVO]
     * @Return: int
     * @Author: luqian
     * @Date: 2024/7/1 4:33 PM
     */
    @Override
    @Transactional
    public int saveTestQuestions(TestQuestionReq testQuestionReq) {
        //先添加试题主表
        TestQuestions testQuestions = BeanUtil.toBean(testQuestionReq, TestQuestions.class);
        int saveQuestionsResult = testQuestionsMapper.insertTestQuestions(testQuestions);
        //获取主表id
        Long testQuestionId = testQuestions.getId();
        //再添加多的一方的表，试题答案表
        for (QuestionResult questionResult : testQuestionReq.getQuestionResultList()) {
            questionResult.setTestQuestionId(testQuestionId);
        }
        int saveBatchQuestionResult = questionResultMapper.saveBatch(testQuestionReq.getQuestionResultList());

        //修改题库表
        //questionBankService.updateQuestionBankCount(testQuestions.getQuestionBlankId(),testQuestionReq.getQuestionResultList() ,testQuestionReq.getQuestionResultList().size());
        return saveQuestionsResult>0&&saveBatchQuestionResult>0?1:0;
    }
   /**
    * @Description: 一对多的修改
    * @Param: [testQuestionVO]
    * @Return: int
    * @Author: luqian
    * @Date: 2024/7/1 4:57 PM
    */
    @Override
    @Transactional
    public int update(TestQuestionReq testQuestionReq) {
        //1。修改主表
        TestQuestions testQuestions = BeanUtil.toBean(testQuestionReq, TestQuestions.class);
        int updateResult = testQuestionsMapper.updateTestQuestions(testQuestions);
        //2。根据主表的id先删除多的一方
//        List<Long> questionResultIdList = new ArrayList<Long>();
//        for (QuestionResult questionResult : testQuestionVO.getQuestionResultList()) {
//            questionResultIdList.add(questionResult.getId());
//        }
//        Long[] questionResultIds = questionResultIdList.toArray(new Long[questionResultIdList.size()]);
        List<Long> questionResultIdList = testQuestionReq.getQuestionResultList().stream().map(QuestionResult::getId).collect(Collectors.toList());
        Long[] questionResultIds = questionResultIdList.toArray(new Long[questionResultIdList.size()]);
        questionResultMapper.deleteQuestionResultByIds(questionResultIds);
        //3。再添加多的一方
        int saveBatch = questionResultMapper.saveBatch(testQuestionReq.getQuestionResultList());
        return updateResult>0&&saveBatch>0?1:0;
    }

    @Override
    public int questionsJoinBank(Long[] testQuestionsIds, Long[] questionBankIds) {
        //首先判断题库中是否存在这个题，如果存在就不做添加了，如果不存在再去做添加，并且更新题库的题目数量
        //假设题目id为1,2,3 的题，添加到 id为2这个题库, 首先通过test_questions判断一下，id为1，2，3的题在2这个题库中是否存在，如果存在就不做操作，
        //  如果不存在先修改test_questions中的question_bank_id这个字段，然后再更新question_bank中对应题库类型的数量
//
//
//        for (Long testQuestionsId : testQuestionsIds) {
//            TestQuestions testQuestions = testQuestionsMapper.selectTestQuestionsById(testQuestionsId);
//            String questionBlankId = testQuestions.getQuestionBlankId();
//        }
        if(testQuestionsIds!=null && testQuestionsIds.length>0 && questionBankIds!=null && questionBankIds.length>0){
            List<TestQuestions> testQuestionsList =  testQuestionsMapper.selectTestQuestionsByIds(testQuestionsIds);
            for (TestQuestions testQuestions : testQuestionsList) {
                //数据模拟 1,2
                String questionBlankId = testQuestions.getQuestionBlankId();
                String[] questionBlankIdArray = questionBlankId.split(",");
                Long[] questionBlankLongIdArray = getStringArray2LongArry(questionBlankIdArray);
                //这个questionBankIds数组是前台传的 例子比如传的就是2
                //数据模拟 2
                //List<Long> questionBlankLongIdByDB = Arrays.asList(questionBlankLongIdArray);
                ArrayList<Long> questionBlankLongIdByDB = new ArrayList<>(Arrays.asList(questionBlankLongIdArray));
                //数据模拟 2,3
              //  List<Long> questionBlankLongIdByFront = Arrays.asList(questionBankIds);
                ArrayList<Long> questionBlankLongIdByFront = new ArrayList<>(Arrays.asList(questionBankIds));

                addQuestionsToBank(questionBlankLongIdByDB, questionBlankLongIdByFront, testQuestions);
                return 1;
            }
        }
        return 0;
    }

    @Override
    public int questionsDelBank(Long[] testQuestionsIds, Long[] questionBankIds) {


        return 0;
    }

    @Override
    public int addQuestionsToBank(List<Long> testQuestionsIds, List<Long> questionBankIds) {
        //1. 做试题和题库的校验
        List<TestQuestions> testQuestionsList = testQuestionsMapper.selectTestQuestionsByIdList(testQuestionsIds);
        if(CollectionUtils.isEmpty(testQuestionsList)){
            throw new RuntimeException("试题不存在");
        }
        List<QuestionBank> questionBankList = questionBankMapper.selectQuestionsBankByIds(questionBankIds);
        if(CollectionUtils.isEmpty(questionBankList)){
            throw new RuntimeException("题库不存在");
        }
        //2. 添加试题到题库中
         //1)找到数据库真实存在的题库，把题库的id，提取出来题库的id,放在一个集合中
        List<Long> bankIdRealByFront = questionBankList.stream().map(QuestionBank::getId).collect(Collectors.toList());
        int updateRowResult = 0;
        for (TestQuestions testQuestions : testQuestionsList) {
            String questionBlankId = testQuestions.getQuestionBlankId();
            List<Long> questionBlankListByDB = new ArrayList<>();
            if(!StringUtils.isEmpty(questionBlankId) ){
                questionBlankListByDB = Arrays.stream(questionBlankId.split(","))
                        .map(Long::parseLong)
                        .collect(Collectors.toList());
            }
            questionBlankListByDB.addAll(bankIdRealByFront);
            List<Long>  questionBlankResult = questionBlankListByDB.stream().distinct().collect(Collectors.toList());
            String questionBlankResultStr = Joiner.on(",").join(questionBlankResult);
            testQuestions.setQuestionBlankId(questionBlankResultStr);
            updateRowResult =  testQuestionsMapper.updateTestQuestions(testQuestions);
        }

        return updateRowResult;
    }



    @Override
    public int delQuestionsToBank(List<Long> testQuestionsIds, List<Long> questionBankIds) {
        //1. 做试题和题库的校验
        List<TestQuestions> testQuestionsList = testQuestionsMapper.selectTestQuestionsByIdList(testQuestionsIds);
        if(CollectionUtils.isEmpty(testQuestionsList)){
            throw new RuntimeException("试题不存在");
        }
        List<QuestionBank> questionBankList = questionBankMapper.selectQuestionsBankByIds(questionBankIds);
        if(CollectionUtils.isEmpty(questionBankList)){
            throw new RuntimeException("题库不存在");
        }
        //前台数据：试题：1,2  题库：2
        //原来数据库的试题1 对应的题库是：1,3
        List<Long> bankIdRealByFront = questionBankList.stream().map(QuestionBank::getId).collect(Collectors.toList());
        int updateRowResult = 0;
        for (TestQuestions testQuestions : testQuestionsList) {
            String questionBlankId = testQuestions.getQuestionBlankId();
            List<Long> questionBlankListByDB = new ArrayList<>();
            if(!StringUtils.isEmpty(questionBlankId) ){
                questionBlankListByDB = Arrays.stream(questionBlankId.split(","))
                        .map(Long::parseLong)
                        .collect(Collectors.toList());
            }
            List<Long> questionBlankResult = questionBlankListByDB.stream().filter(bankId -> !bankIdRealByFront.contains(bankId)).collect(Collectors.toList());
            if(questionBlankResult.size()<=0){
                throw new RuntimeException("试题至少存在一个题库中！");
            }
            String questionBlankResultStr = Joiner.on(",").join(questionBlankResult);
            testQuestions.setQuestionBlankId(questionBlankResultStr);
            updateRowResult =  testQuestionsMapper.updateTestQuestions(testQuestions);
        }
        return updateRowResult;
    }


    public boolean addQuestionsToBank(List<Long> questionBlankLongIdByDB, List<Long> questionBlankLongIdByFront, TestQuestions testQuestions){
        for (Long blankIdByFront : questionBlankLongIdByFront) {
            boolean exists = questionBlankLongIdByDB.contains(blankIdByFront);
            if(!exists){
                //说明这个题库中不存在，需要添加
                questionBlankLongIdByDB.add(blankIdByFront);
                //把集合转换为逗号拼接的字符串
                String questionBlankLongIdByDBStr = Joiner.on(",").join(questionBlankLongIdByDB);
                testQuestions.setQuestionBlankId(questionBlankLongIdByDBStr);
                //更新测试题的归属题库的字段
                testQuestionsMapper.updateTestQuestions(testQuestions);
                //更新题库中对应题目类型的数量
                questionBankMapper.updateQuestionCountById(blankIdByFront,testQuestions);
            }
        }

       return true;
    }
    public Long[] getStringArray2LongArry(String[] strArray){
        Long[] longArry = new Long[strArray.length];
        for (int i=0;i<strArray.length;i++){
            longArry[i] = Long.parseLong(strArray[i]);
        }
        return longArry;
    }
    public static void main(String[] args) {
        Long[] testQuestionsIds = new Long[]{2L};
        List<Long> bankIdRealByFront = Arrays.asList(testQuestionsIds);
        Long[] questionBankIds = new Long[]{1L,3L};
        List<Long> questionBlankListByDB = Arrays.asList(questionBankIds);

        // 获取差集
        //List<Long> difference1 = list1.stream().filter(element -> !list2.contains(element)).collect(Collectors.toList());
        // 获取交集
       // List<Long> intersection = list1.stream().filter(list2::contains).collect(Collectors.toList());

        List<Long> collect = questionBlankListByDB.stream().filter(item -> !bankIdRealByFront.contains(item)).collect(Collectors.toList());

        System.out.println(collect);


    }
}
